package com.canbot.u05.activity.shoppingGuide.sales;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.sales.SellInfo;
import com.canbot.u05.bean.sales.VoiceInfo;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.update.GeneralDialog;
import com.canbot.u05.utils.Config;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.CenterDialogCounsel;
import com.canbot.u05.view.CustomLineEditTextDialog;
import com.canbot.u05.view.IButtonClickListerner;
import com.canbot.u05.widget.LoadingDialogUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 售卖宣传吆喝语音界面
 */

public class SalesCryActivity extends BaseActivityNoTitle {

        private CenterDialogCounsel dialogCounsel;

        private ListView listView;

        private CheckBox btnCheck;

        private MyAdapter myAdapter = new MyAdapter(this);

        private List<VoiceInfo> list = new ArrayList<>();

        private int oldId = -1;

        private String pathVoice;

        private int type;

        private int index;

        private CheckBox checkBox;

        private String title;

        private int sellId;

        private int random;

        private String sellUuid;

        private String tag;

        private boolean save;

        private GeneralDialog dialogcounsel1;

        private GeneralDialog dialogcounsel2;

        private SellInfo sellInfo;

        private Dialog dialogLoading;

        private String saleTitle;

        private LinearLayout linearLayout;

        private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        startActivity(new Intent(SalesCryActivity.this, SellModePropagandaActivity.class));
                        finish();
                        overridePendingTransition(R.anim.face_zoom_enter,
                                R.anim.face_zoom_exit);
                }
        };

        private TextView textView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.sales_cry_activity);
                linearLayout = (LinearLayout)findViewById(R.id.ll_no_data);
                textView= (TextView) findViewById(R.id.teach_uu_first_word2);
                String a = getResources().getString(R.string.teach_uu_first_word2);
                String b = String.format(a, Config.ROBOT_NAME);


                boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.SHOPPING_GUIDE_DIR + "sale/rwbjdr_cxlk_u05_001.wav");
                if (!isSuccess) {
                        ToastTools.newInstance(this).showText(getString(R.string.network_error));
                }
                Intent intent = getIntent();
                tag = intent.getStringExtra("tag");
                saleTitle = intent.getStringExtra("saleTitle");
                if ("edit".equals(tag)) {
                        linearLayout.setVisibility(View.INVISIBLE);
                        //说明是编辑
                        // SellInfo sellInfo = (SellInfo) intent.getSerializableExtra("sellInfo");
                        String s = intent.getStringExtra("sellInfo");
                        sellInfo = new Gson().fromJson(s, SellInfo.class);
                        sellUuid = sellInfo.getUuid();
                        sellId = sellInfo.getId();
                        title = sellInfo.getTitle();
                        random = sellInfo.getRandom();

                        List<VoiceInfo> voiceInfo = sellInfo.getVoiceInfo();
                        list.addAll(voiceInfo);
                        myAdapter.notifyDataSetChanged();

                }else {
                        linearLayout.setVisibility(View.VISIBLE);
                        textView.setText(b);
                }
                initData();
                initView();
        }

        private void initView() {
                listView = (ListView) findViewById(R.id.listView);
                checkBox = (CheckBox) findViewById(R.id.btn_Check);
                TextView textView = (TextView) findViewById(R.id.text_title);
                if (title != null) {
                        textView.setText(title + "");
                }

                btnCheck = (CheckBox) findViewById(R.id.btn_Check);
                if (random == 1) {
                        checkBox.setSelected(true);
                }
                else {
                        checkBox.setSelected(false);
                }
                btnCheck.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                        }
                });

                btnCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                        }
                });

                listView.setAdapter(myAdapter);
        }

        private void initData() {

//        for (int i = 0;i <30;i++) {
//            DBCryInfo info = new DBCryInfo(i,"吆喝语音"+ i);
//            list.add(info);
//        }
        }

        /**
         * 完成
         *
         * @param view
         */
        public void complete(View view) {
                if ("edit".equals(tag)) {
                        if (list == null || list.size() == 0) {
                                ToastTools.newInstance(this).showText(getString(R.string.not_select_voice));
                                return;
                        }
                        dialogcounsel2 = new GeneralDialog(this, "提示", "取消", "确认", "是否确定修改？", false, new GeneralDialog.IButtonClickListerner() {
                                @Override
                                public void doBtnRight() {
                                        editToPad(sellUuid, title);
                                        dialogcounsel2.dismiss();
                                }

                                @Override
                                public void doBtnLeft() {
                                        dialogcounsel2.dismiss();
//                    finish();
                                }
                        });
                        dialogcounsel2.show();


                }
                else {
                        if (list == null || list.size() == 0) {
                                ToastTools.newInstance(this).showText(getString(R.string.not_select_voice));
                                return;
                        }
                        dialogcounsel1 = new GeneralDialog(this, "提示", "取消", "确定", "是否确定保存", false, new GeneralDialog.IButtonClickListerner() {
                                @Override
                                public void doBtnRight() {

                                        if (TextUtils.isEmpty(saleTitle)) {
                                                ToastTools.newInstance(SalesCryActivity.this).showText(getString(R.string.please_first_named));
                                                return;
                                        }
                                        dialogcounsel1.dismiss();
                                        updateToPad(saleTitle);

                                }

                                @Override
                                public void doBtnLeft() {
                                        dialogcounsel1.dismiss();
//                    finish();
                                }
                        });
                        dialogcounsel1.show();
                }
        }

        /**
         * 返回键   进入售卖宣传主界面
         */
        public void CryBack(View view) {
//        if(save){
//            Toast.makeText(this, "您已经保存了,无需再保存", Toast.LENGTH_SHORT).show();
//            finish();
//            return;
//        }

//        if(list==null||list.size()<1){
//            Toast.makeText(this, "内容为空，请先添加数据，再提交", Toast.LENGTH_SHORT).show();
//            return;
//        }
                startActivity(new Intent(this, SellModePropagandaActivity.class));
                finish();
                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
        }


        /**
         * 数据提交
         */
        private void updateToPad(String text) {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.data_upload));
                int random = checkBox.isChecked() ? 1 : 0;
                Log.d("SalesCryActivity", "判断语音是否是随机：random:" + random);

                final String uuid = UUID.randomUUID().toString().replace("-", "");
                SellInfo sellInfo = new SellInfo(uuid, text, System.currentTimeMillis(), list, random);


                Gson g = new Gson();
                String toJson = g.toJson(sellInfo);
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<String> stringCall = salesApi.addSell(toJson);
                stringCall.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                Message message = Message.obtain();
                                if (response.body() != null) {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                        ToastTools.newInstance(SalesCryActivity.this).showText(getString(R.string.save_successfully));

                                        mHandler.sendEmptyMessage(1);
                                }
                                else {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                ToastTools.newInstance(SalesCryActivity.this).showText(getString(R.string.submit_failure));
                        }
                });

                Log.d("SalesCryActivity", "售卖提交内容 " + toJson);

        }



        /**
         * 修改提交
         */
        private void editToPad(String id, String text) {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this,getString(R.string.data_upload));
                int random = checkBox.isChecked() ? 1 : 0;
                sellInfo.setUuid(id);
                sellInfo.setDate(System.currentTimeMillis());
                sellInfo.setRandom(random);
                sellInfo.setTitle(text);
                sellInfo.setVoiceInfo(list);
                Log.e("SalesCryActivity", "list:" + list);
                Log.e("SalesCryActivity", "编辑sellInfo:" + sellInfo);
                Gson g = new Gson();
                String toJson = g.toJson(sellInfo);
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<String> stringCall = salesApi.editSell(toJson);
                stringCall.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                ToastTools.newInstance(SalesCryActivity.this).showText(getString(R.string.modify_successfully));
                                mHandler.sendEmptyMessage(1);
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                ToastTools.newInstance(SalesCryActivity.this).showText(getString(R.string.modify_failed));
                        }
                });

        }


        /**
         * 添加键   进入新建吆喝宣传
         */
        private final static int SELLVOICECODE = 222;

        public void CryAdd(View view) {


                Intent intent = new Intent(SalesCryActivity.this, SalesQuestionVoiceActivity.class);
                startActivityForResult(intent, SELLVOICECODE);
                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
        }

        class ViewHodler {

                private RelativeLayout layout;

                private ImageView imageLine, imageView;

                private TextView title;

                private Button btnDetele;
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                Log.d("SalesAddActionActivity", "返回来的数据是 voice" + data);
                if (requestCode == SELLVOICECODE && resultCode == RESULT_OK && data != null) {
                        Bundle voice = data.getBundleExtra("voice");
                        if (voice != null) {
                                if (list != null){
                                        index = list.size() + 1;
                                }
                                pathVoice = voice.getString("path");
                                type = voice.getInt("type");
                                VoiceInfo voiceInfo = new VoiceInfo(index, pathVoice, type);
                                list.add(voiceInfo);
                                linearLayout.setVisibility(View.GONE);
                                myAdapter.notifyDataSetChanged();

                                Log.d("SalesAddActionActivity", "返回来的数据是 voice" + pathVoice + ",," + type);
                        }
                }

        }

        //Adapter
        public class MyAdapter extends BaseAdapter {

                public Context context;

                public MyAdapter(Context context) {
                        this.context = context;
                }

                @Override
                public int getCount() {
                        return list.size();
                }

                @Override
                public Object getItem(int position) {
                        return list.get(position);
                }

                @Override
                public long getItemId(int position) {
                        return position;
                }

                @Override
                public View getView(final int position, View convertView, ViewGroup parent) {
                        final ViewHodler hodler;
                        if (convertView == null) {
                                hodler = new ViewHodler();
                                convertView = LayoutInflater.from(context).inflate(R.layout.counsel_listview_cell, null);
                                hodler.layout = (RelativeLayout) convertView.findViewById(R.id.layout);
                                hodler.imageLine = (ImageView) convertView.findViewById(R.id.image_line);
                                hodler.imageView = (ImageView) convertView.findViewById(R.id.imageView);
                                hodler.title = (TextView) convertView.findViewById(R.id.title);
                                hodler.btnDetele = (Button) convertView.findViewById(R.id.btn_delete);
                                convertView.setTag(hodler);
                        }
                        else {
                                hodler = (ViewHodler) convertView.getTag();
                        }
                        final VoiceInfo info = list.get(position);
                        int i = position+1;
                        hodler.title.setText("促销语音" + i);

                        //选中listview的Item颜色改变
                        hodler.layout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
//                                        ToastUtil.show(context, "点到的是" + hodler.title.getText().toString());
                                        if (oldId == -1) {    //第一次点击
                                                oldId = position;
                                                hodler.imageLine.setVisibility(View.VISIBLE);
                                                hodler.title.setTextColor(getResources().getColor(R.color.counsel_listview_title));
                                                hodler.imageView.setBackground(getResources().getDrawable(R.drawable.audio_press));
                                                hodler.btnDetele.setBackground(getResources().getDrawable(R.drawable.counsel_delete_press));

                                        }
                                        else {   //非第一次点击   把上一次点击的 改变
                                                hodler.imageLine.setVisibility(View.GONE);
                                                hodler.imageView.setBackground(getResources().getDrawable(R.drawable.audio));
                                                hodler.title.setTextColor(getResources().getColor(R.color.counsel_listview_title_press));
                                                hodler.btnDetele.setBackground(getResources().getDrawable(R.drawable.counsel_delete));
                                                oldId = position;
                                        }
                                        myAdapter.notifyDataSetChanged();
                                }
                        });

                        if (oldId != -1 && position == oldId) {   // 为点击 item
                                hodler.imageLine.setVisibility(View.VISIBLE);
                                hodler.imageView.setBackground(getResources().getDrawable(R.drawable.audio_press));
                                hodler.title.setTextColor(getResources().getColor(R.color.counsel_listview_title));
                                hodler.btnDetele.setBackground(getResources().getDrawable(R.drawable.counsel_delete_press));
                        }
                        else {
                                hodler.imageLine.setVisibility(View.GONE);
                                hodler.imageView.setBackground(getResources().getDrawable(R.drawable.audio));
                                hodler.title.setTextColor(getResources().getColor(R.color.counsel_listview_title_press));
                                hodler.btnDetele.setBackground(getResources().getDrawable(R.drawable.counsel_delete));
                        }

                        //删除一行button
                        hodler.btnDetele.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                        dialogCounsel = new CenterDialogCounsel(context,
                                                R.style.centerdialog, "确定删除选中的对话？", "确认", "取消",
                                                new IButtonClickListerner() {

                                                        @Override
                                                        public void doBtnRight() {
                                                                ToastTools.newInstance(SalesCryActivity.this).showText(getString(R.string.delete_confirmation));
                                                                //确认
                                                                list.remove(position);
                                                                myAdapter.notifyDataSetChanged();
                                                        }

                                                        @Override
                                                        public void doBtnLeft() {
                                                                dialogCounsel.dismiss();
                                                        }
                                                });
                                        dialogCounsel.show();
                                }
                        });
                        return convertView;
                }
        }

        private static final int TIMEOUT = 100;//超时时间100s

        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }
}
